"""
好友相关视图函数
"""
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.db.models import Q
from django.views.decorators.http import require_http_methods
import json

from .models import Friendship, Conversation
from users.models import User


@login_required
def search_users(request):
    """搜索用户"""
    query = request.GET.get('q', '').strip()
    
    if not query:
        return JsonResponse({'success': True, 'users': []})
    
    # 搜索用户名或昵称匹配的用户（排除自己）
    users = User.objects.filter(
        Q(username__icontains=query) | Q(nickname__icontains=query)
    ).exclude(id=request.user.id)[:20]
    
    # 获取当前用户的好友ID列表
    friend_ids = set()
    friendships = Friendship.objects.filter(
        Q(from_user=request.user, status='accepted') |
        Q(to_user=request.user, status='accepted')
    )
    for friendship in friendships:
        if friendship.from_user == request.user:
            friend_ids.add(friendship.to_user.id)
        else:
            friend_ids.add(friendship.from_user.id)
    
    # 获取待处理的好友请求
    pending_requests = {}
    sent_requests = Friendship.objects.filter(
        from_user=request.user, 
        status='pending'
    ).values_list('to_user_id', flat=True)
    received_requests = Friendship.objects.filter(
        to_user=request.user, 
        status='pending'
    ).values_list('from_user_id', flat=True)
    
    for user_id in sent_requests:
        pending_requests[user_id] = 'sent'
    for user_id in received_requests:
        pending_requests[user_id] = 'received'
    
    users_data = []
    for user in users:
        is_friend = user.id in friend_ids
        pending_status = pending_requests.get(user.id, None)
        
        users_data.append({
            'id': user.id,
            'username': user.username,
            'nickname': user.nickname or user.username,
            'avatar': user.avatar.url if user.avatar else None,
            'is_friend': is_friend,
            'pending_status': pending_status,
        })
    
    return JsonResponse({'success': True, 'users': users_data})


@login_required
@require_http_methods(["POST"])
def send_friend_request(request, user_id):
    """发送好友请求"""
    to_user = get_object_or_404(User, id=user_id)
    
    if to_user == request.user:
        return JsonResponse({'success': False, 'message': '不能添加自己为好友'})
    
    # 检查是否已经是好友
    if Friendship.are_friends(request.user, to_user):
        return JsonResponse({'success': False, 'message': '你们已经是好友了'})
    
    # 检查是否已经发送过请求
    existing_request = Friendship.objects.filter(
        Q(from_user=request.user, to_user=to_user) |
        Q(from_user=to_user, to_user=request.user)
    ).first()
    
    if existing_request:
        if existing_request.status == 'pending':
            return JsonResponse({'success': False, 'message': '好友请求已发送，请等待对方确认'})
        elif existing_request.status == 'rejected':
            # 如果之前被拒绝，可以重新发送
            existing_request.status = 'pending'
            existing_request.from_user = request.user
            existing_request.to_user = to_user
            existing_request.save()
            return JsonResponse({'success': True, 'message': '好友请求已重新发送'})
    
    # 创建新的好友请求
    Friendship.objects.create(
        from_user=request.user,
        to_user=to_user,
        status='pending'
    )
    
    return JsonResponse({'success': True, 'message': '好友请求已发送'})


@login_required
@require_http_methods(["POST"])
def accept_friend_request(request, request_id):
    """接受好友请求"""
    friendship = get_object_or_404(
        Friendship, 
        id=request_id, 
        to_user=request.user, 
        status='pending'
    )
    
    friendship.status = 'accepted'
    friendship.save()
    
    return JsonResponse({'success': True, 'message': '已接受好友请求'})


@login_required
@require_http_methods(["POST"])
def reject_friend_request(request, request_id):
    """拒绝好友请求"""
    friendship = get_object_or_404(
        Friendship, 
        id=request_id, 
        to_user=request.user, 
        status='pending'
    )
    
    friendship.status = 'rejected'
    friendship.save()
    
    return JsonResponse({'success': True, 'message': '已拒绝好友请求'})


@login_required
@require_http_methods(["POST"])
def remove_friend(request, user_id):
    """删除好友"""
    other_user = get_object_or_404(User, id=user_id)
    
    friendship = Friendship.objects.filter(
        Q(from_user=request.user, to_user=other_user, status='accepted') |
        Q(from_user=other_user, to_user=request.user, status='accepted')
    ).first()
    
    if not friendship:
        return JsonResponse({'success': False, 'message': '你们不是好友关系'})
    
    friendship.delete()
    
    return JsonResponse({'success': True, 'message': '已删除好友'})


@login_required
def get_friends_list(request):
    """获取好友列表"""
    friends = Friendship.get_friends(request.user)
    
    friends_data = []
    for friend in friends:
        # 检查是否有会话
        conversation = Conversation.objects.filter(
            participants=request.user
        ).filter(
            participants=friend
        ).first()
        
        friends_data.append({
            'id': friend.id,
            'username': friend.username,
            'nickname': friend.nickname or friend.username,
            'avatar': friend.avatar.url if friend.avatar else None,
            'has_conversation': conversation is not None,
            'conversation_id': conversation.id if conversation else None,
        })
    
    return JsonResponse({'success': True, 'friends': friends_data})


@login_required
def get_friend_requests(request):
    """获取好友请求列表"""
    # 收到的请求
    received_requests = Friendship.objects.filter(
        to_user=request.user,
        status='pending'
    ).select_related('from_user')
    
    # 发送的请求
    sent_requests = Friendship.objects.filter(
        from_user=request.user,
        status='pending'
    ).select_related('to_user')
    
    received_data = []
    for req in received_requests:
        received_data.append({
            'id': req.id,
            'user': {
                'id': req.from_user.id,
                'username': req.from_user.username,
                'nickname': req.from_user.nickname or req.from_user.username,
                'avatar': req.from_user.avatar.url if req.from_user.avatar else None,
            },
            'created_at': req.created_at.isoformat(),
        })
    
    sent_data = []
    for req in sent_requests:
        sent_data.append({
            'id': req.id,
            'user': {
                'id': req.to_user.id,
                'username': req.to_user.username,
                'nickname': req.to_user.nickname or req.to_user.username,
                'avatar': req.to_user.avatar.url if req.to_user.avatar else None,
            },
            'created_at': req.created_at.isoformat(),
        })
    
    return JsonResponse({
        'success': True,
        'received': received_data,
        'sent': sent_data
    })


@login_required
def friend_profile(request, user_id):
    """查看好友主页"""
    profile_user = get_object_or_404(User, id=user_id)
    
    # 不能查看自己的主页（使用这个视图）
    if profile_user == request.user:
        return redirect('users:profile')
    
    # 检查是否是好友
    is_friend = Friendship.are_friends(request.user, profile_user)
    
    # 检查是否有待处理的好友请求
    pending_request = Friendship.objects.filter(
        Q(from_user=request.user, to_user=profile_user, status='pending') |
        Q(from_user=profile_user, to_user=request.user, status='pending')
    ).first()
    
    pending_status = None
    if pending_request:
        if pending_request.from_user == request.user:
            pending_status = 'sent'
        else:
            pending_status = 'received'
    
    context = {
        'profile_user': profile_user,
        'is_friend': is_friend,
        'pending_status': pending_status,
    }
    
    return render(request, 'social/friend_profile.html', context)
